#! tclsh ps2pdf.tcl

proc absolve {fname} {
	regsub -all "\\\\" $fname "/" fname
	if {[regexp -nocase "^\[a-z\]+:" $fname]} {return $fname}
	set pwd [pwd]
	if {[string compare [string index $fname 0] "\/"] == 0} {
		if {![regexp -nocase "^\[a-z\]+:" $pwd drive]} {return $fname}
		return $drive$fname
	}
	return $pwd/$fname
}

if {[catch {

	if {[llength $argv] == 0} {puts "Usage: tclsh ps2pdf.tcl file.ps \[file.pdf\]"; exit 0}
	set psfile [absolve [lindex $argv 0]]
	if {[string compare [file extension $psfile] .ps] != 0} {error "First argument should be a file with extension ps"}
	if {[llength $argv] > 1} {
		set pdffile [absolve [lindex $argv 1]]
		if {[string compare [file extension $pdffile] .pdf] != 0} {error "Second argument should be a file with extension pdf"}
	} else {
		regsub ".ps\$" $psfile ".pdf" pdffile
	} 
	
	set found 0
	foreach path [split $env(PATH) ";"] {
		set found [regexp "(.*\\\\gs\[0-9\]\[0-9.\]*)\\\\bin" $path dummy gspath]
		if $found break
	}
	if "!$found" {error "GhostScript path not found"}
	cd "[regsub -all "\\\\" $gspath "/"]/lib"
	
	puts "ps2pdf.bat \"$psfile\" \"$pdffile\""
	exec ps2pdf.bat "$psfile" "$pdffile"

} msg]} {
	puts "Error: $msg"
	#sleep 10
	exit 1
} 
